package com.cwvs.cat;


import java.util.ArrayList;
import java.util.List;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import org.json.JSONException;
import org.json.JSONObject;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.im.v2.AVIMClient;
import com.avos.avoscloud.im.v2.callback.AVIMClientCallback;
import com.avoscloud.chat.service.UserService;
import com.avoscloud.chat.service.chat.IM;
import com.avoscloud.chat.service.event.LoginFinishEvent;
import com.avoscloud.chat.util.NetAsyncTask;
import com.avoscloud.chat.util.Utils;
import com.cwvs.cat.adapter.WelcomeViewPagerAdapter;
import com.cwvs.cat.bean.User;
import com.cwvs.cat.net.Port;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.Toast;
import com.cwvs.cat.myview.BaseActivity;

import de.greenrobot.event.EventBus;

public class WelcomeAc extends BaseActivity {

	private Runnable enterAppRunnable;
	private SharedPreferences sharedPreferences;
	private Editor editor;
	private final String USERINFO = "user";
	private String username,userpass,type;
	private Handler handler;
	//首页图片滚动
	private ViewPager viewPager;
	private int oldPosition1 = 0;//上一次页面位置
	private WelcomeViewPagerAdapter viewAdapter;
	private int currentItem1;//页面当前所处的位置
	private boolean firstLogin = true;
	private View layout1 = null;
	private View layout2 = null;
	private View layout3 = null;
	private View layout4 = null;
	private View layout5 = null;
	private List<View> viewList;
	private ImageView pageView;

	private View framelayout1;
	private ImageView imageview;
	
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.welcomac);
		setHeaderGone();
		
		framelayout1 = findViewById(R.id.framelayout1);
		imageview= (ImageView) findViewById(R.id.imageview);
		
		sharedPreferences = getSharedPreferences(USERINFO,0);
		firstLogin = sharedPreferences.getBoolean("firstLogin", true);
		username = sharedPreferences.getString("username", "");
		userpass = sharedPreferences.getString("userpass", "");
		type = sharedPreferences.getString("type", "");
		
		
		if (firstLogin) {
			framelayout1.setVisibility(View.VISIBLE);
			imageview.setVisibility(View.GONE);
			firstEnter();
			editor = sharedPreferences.edit();
			editor.putBoolean("firstLogin",false);
			editor.commit();
		}else {
			framelayout1.setVisibility(View.GONE);
			imageview.setVisibility(View.VISIBLE);
			handler = new Handler();
			enterAppRunnable = new Runnable() {
				@SuppressLint("ShowToast")
				@Override
				public void run() {
					if (CheckNetwork()) {
						if (!username.equals("")) {
							Login();
						}else {
							Intent intent = new Intent(WelcomeAc.this,LoginActivity.class);
							startActivity(intent);
							finish();
							overridePendingTransition(R.anim.slide_right_in_click, R.anim.slide_right_out_click);
						}
					}else {
						Toast.makeText(WelcomeAc.this, "网络连接异常...", 200).show();
					}
					return;
				}
			};
			handler.postDelayed(enterAppRunnable,2000);
		}
		
	}
	
	
	
	
	
	private void firstEnter(){
		initData();
		viewPager = (ViewPager) findViewById(R.id.welcome_viewpager);
		viewAdapter = new WelcomeViewPagerAdapter(WelcomeAc.this,viewList);
		viewPager.setAdapter(viewAdapter);
		viewPager.setOnPageChangeListener(new MyOnPageChangeListener1());
	}


	private class MyOnPageChangeListener1 implements OnPageChangeListener{
		public void onPageSelected(int position) {
			System.out.println("position==="+position);
			//更新当前页面
			currentItem1 = position;
			currentItem1 = position;
			oldPosition1 = position;
			if (position == 4) {
				viewPager.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						Intent intent =new Intent(WelcomeAc.this,LoginActivity.class);
						startActivity(intent);
						overridePendingTransition(R.anim.slide_right_in_click, R.anim.slide_right_out_click);
					}
				});
			}
		}
		public void onPageScrollStateChanged(int arg0) {

		}
		public void onPageScrolled(int arg0, float arg1, int arg2) {

		}
	}
	private void initData() {
		viewList = new ArrayList<View>();
		LayoutInflater inFlater = getLayoutInflater();
		layout1 = inFlater.inflate(R.layout.page1, null);
		layout2 = inFlater.inflate(R.layout.page2, null);
		layout3 = inFlater.inflate(R.layout.page3, null);
		layout4 = inFlater.inflate(R.layout.page4, null);
		viewList.add(layout1);
		viewList.add(layout2);
		viewList.add(layout3);
		viewList.add(layout4);

		pageView = (ImageView) layout4.findViewById(R.id.go);
		pageView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent =new Intent(WelcomeAc.this,LoginActivity.class);
				startActivity(intent);
				overridePendingTransition(R.anim.slide_right_in_click, R.anim.slide_right_out_click);
				finish();
			}
		});
	}
	
	
	private void Login(){
		AjaxParams params = new AjaxParams();
		params.put("account",username);
		params.put("password",userpass);
		params.put("type",type);
		System.out.println("params==="+params.toString());
		FinalHttp fh = new FinalHttp();
		fh.post(Port.Login,params, new AjaxCallBack<Object>() {

			@Override
			public void onFailure(Throwable t, int errorNo, String strMsg) {
				// TODO Auto-generated method stub
				super.onFailure(t, errorNo, strMsg);
				startActivity(LoginActivity.class);
			}

			@Override
			public void onSuccess(Object t) {
				// TODO Auto-generated method stub
				super.onSuccess(t);
				JSONObject json;
				try {
					json = new JSONObject(t.toString());
					int code = json.getInt("code");
					if (code==0) {
						Applications.user = User.createFromJson(json.getJSONObject("item"));
						login();
						userLcation();
						startActivity(MainActivity.class);
						finish();
					}else {
						startActivity(LoginActivity.class);
						//Toast.makeText(WelcomeAc.this,json.getString("msg"),2000).show();
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
	}
	private void userLcation(){
		AjaxParams params = new AjaxParams();
		params.put("x","120.0000000000");
		params.put("y","30.0000000000");
		params.put("token", Applications.user.token);
		System.out.println("params==="+params.toString());
		FinalHttp fh = new FinalHttp();
		fh.post(Port.userLcation,params, new AjaxCallBack<Object>() {

			@Override
			public void onFailure(Throwable t, int errorNo, String strMsg) {
				// TODO Auto-generated method stub
				super.onFailure(t, errorNo, strMsg);
			}

			@Override
			public void onSuccess(Object t) {
				// TODO Auto-generated method stub
				super.onSuccess(t);
				//	System.out.println(t.toString());
				JSONObject json;
				try {
					json = new JSONObject(t.toString());
					int code = json.getInt("code");
					if (code==0) {

					}else {
						//Toast.makeText(LoginActivity.this,json.getString("msg"),2000).show();
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
	}
	
	private  boolean CheckNetwork() {
		boolean flag = false;
		try {
			ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			if (cwjManager.getActiveNetworkInfo() != null)
				flag = cwjManager.getActiveNetworkInfo().isAvailable();
		} catch (Exception e) {

		}
		return flag;
	}
	
	private void login() {	
		if (AVUser.getCurrentUser() != null) {
			UserService.updateUserInfo();
			handler2.sendEmptyMessageDelayed(GO_MAIN_MSG, SPLASH_DURATION);
		} else {
			handler2.sendEmptyMessageDelayed(GO_LOGIN_MSG, SPLASH_DURATION);
		}
	}
	public static final int SPLASH_DURATION = 2000;
	private static final int GO_MAIN_MSG = 1;
	private static final int GO_LOGIN_MSG = 2;

	private Handler handler2 = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case GO_MAIN_MSG:
				// 已登录leancloud

				break;
			case GO_LOGIN_MSG:
				// 未登录leancloud
				avReg();
				avLogin();
				break;
			}
		}
	};

	public void avReg() {
		new NetAsyncTask(WelcomeAc.this) {
			@Override
			protected void doInBack() throws Exception {
				AVUser user = UserService.signUp(username,userpass);
				user.setFetchWhenSave(true);
				user.save();
			}

			@Override
			protected void onPost(Exception e) {
				if (e != null) {
					Utils.toast("注册失败" + e.getMessage());
				} else {
					Applications.avUser = AVUser.getCurrentUser();
					
					Utils.toast(R.string.registerSucceed);
					UserService.updateUserLocation();
					
					EventBus eventBus = EventBus.getDefault();
					eventBus.post(new LoginFinishEvent());

					IM im = IM.getInstance();
					im.setupWithCurrentUser();
					//im.open(AVUser.getCurrentUser().getObjectId());
					im.open(Applications.user.id);
				}
			}
		}.execute();
	}

	public void avLogin() {
		new NetAsyncTask(WelcomeAc.this) {
			@Override
			protected void doInBack() throws Exception {
				AVUser.logIn(username, userpass);
			}

			@Override
			protected void onPost(Exception e) {
				if (e != null) {
					Utils.toast(e.getMessage());
				} else {
					Applications.avUser = AVUser.getCurrentUser();
					System.out.println("user===================="+AVUser.getCurrentUser().getObjectId());
					UserService.updateUserLocation();
					
					EventBus eventBus = EventBus.getDefault();
					eventBus.post(new LoginFinishEvent());

					IM im = IM.getInstance();
					im.setupWithCurrentUser();
					//im.open(AVUser.getCurrentUser().getObjectId());
					im.open(Applications.user.id);
				}
			}
		}.execute();
	}

}
